import json
import re

import requests


def get_stock_list():
    base_url = "https://query.sse.com.cn/sseQuery/commonQuery.do"
    params = {
        "jsonCallBack": "jsonpCallback99938769",
        "STOCK_TYPE": "1",
        "REG_PROVINCE": "",
        "CSRC_CODE": "",
        "STOCK_CODE": "",
        "sqlId": "COMMON_SSE_CP_GPJCTPZ_GPLB_GP_L",
        "COMPANY_STATUS": "2,4,5,7,8",
        "type": "inParams",
        "isPagination": "true",
        "pageHelp.cacheSize": "1",
        "pageHelp.beginPage": "1",
        "pageHelp.pageSize": "25",
        "pageHelp.pageNo": "1",
        "pageHelp.endPage": "1",
        "_": "1761549095406"
    }

    headers = {
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Referer": "https://www.sse.com.cn/",
        "Sec-Fetch-Dest": "script",
        "Sec-Fetch-Mode": "no-cors",
        "Sec-Fetch-Site": "same-site",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
        "sec-ch-ua": "\"Google Chrome\";v=\"141\", \"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"141\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\""
    }

    cookies = {
        "ba17301551dcbaf9_gdp_session_id": "521ffd0b-547b-494e-9865-533b771337e8",
        "gdp_user_id": "gioenc-00a800gb%2Cg114%2C5877%2C9e47%2Cbc6720ca4351",
        "ba17301551dcbaf9_gdp_session_id_sent": "521ffd0b-547b-494e-9865-533b771337e8",
        "ba17301551dcbaf9_gdp_sequence_ids": "{%22globalKey%22:9%2C%22VISIT%22:2%2C%22PAGE%22:3%2C%22VIEW_CLICK%22:6}"
    }

    response = requests.get(
        base_url,
        params=params,
        headers=headers,
        cookies=cookies
    )

    # print(response.status_code)
    print(response.text)
    print(type(response.text))
    if response.status_code == 200:
        # 正则匹配括号内的 JSON 部分
        match = re.search(r'\((.*)\)', response.text)
        if match:
            json_str = match.group(1)  # 提取出 {}
            try:
                json_data = json.loads(json_str)
                result = json_data["result"]
                for item in result:
                    print(f"股票名称={item['COMPANY_ABBR']},股票代码={item['A_STOCK_CODE']}")
                print("解析结果:", json_data)  # 输出: {}
            except json.JSONDecodeError as e:
                print("JSON 解析错误:", e)
        else:
            print("未找到有效的 JSONP 结构")


if __name__ == '__main__':
    get_stock_list()
